package org.cfx.auth.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.cfx.auth.domain.dto.LoginDto;
import org.cfx.basic.service.impl.TokenService;
import org.cfx.org.domain.Employee;
import org.cfx.org.domain.dto.EmployeeDto;
import org.cfx.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/user")
public class UserController {
 
    @Autowired
    private IEmployeeService userService;
 
    @Autowired
    private TokenService tokenService;
 
    @PutMapping("/login")
    public EmployeeDto login(@RequestBody LoginDto loginDto, HttpServletRequest request){
        EmployeeDto dto = new EmployeeDto();
        Employee user = this.userService.login2(loginDto);
        if (user != null) { //成功
            String userAgentStr = request.getHeader("user-agent");
            //生成token
            String token = this.tokenService.generateToken(userAgentStr, loginDto.getUsername(),user);
            //保存token
            this.tokenService.save(token, dto);
            //组织前台需要的信息
            dto.setToken(token);
            dto.setIsLogin(true);
            dto.setTokenCreatedDate(System.currentTimeMillis());
            dto.setTokenExpiryDate(System.currentTimeMillis() + 7200000);
        } else { //失败
            dto.setIsLogin(false);
        }
        return dto;
    }
 
 
}